<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生成并下载 Excel 文件</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>

</head>

<body>
    <button id="downloadBtn">生成并下载 Excel 文件</button>

    <script>
        $(document).ready(function () {
            $("#downloadBtn").click(function () {
                // 创建工作簿对象
                var workbook = XLSX.utils.book_new();

                // 创建工作表对象
                var worksheet = XLSX.utils.aoa_to_sheet([
                    ['姓名', '年龄', '性别'],
                    ['张三', 25, '男'],
                    ['李四', 30, '女'],
                    ['王五', 35, '男']
                ]);

                // 将工作表添加到工作簿
                XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

                // 将工作簿转换为二进制数据流
                var workbookData = XLSX.write(workbook, { type: 'binary' });

                // 将二进制数据流转换为 Blob 对象
                var blob = new Blob([s2ab(workbookData)], { type: 'application/octet-stream' });

                // 创建下载链接
                var downloadLink = document.createElement('a');
                downloadLink.href = URL.createObjectURL(blob);
                downloadLink.download = 'example.xlsx';

                // 模拟点击下载链接
                downloadLink.click();
            });

            // 字符串转字节数组
            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i < s.length; i++) {
                    view[i] = s.charCodeAt(i) & 0xFF;
                }
                return buf;
            }
        });
    </script>
</body>

</html>